/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gu
 * @date 2020/5/26 9:03
 */
public class ClauseUtil {

  private static Pattern order = Pattern.compile("(^| )order by .*$");
  private static Pattern where = Pattern.compile("(^| )where .*$");
  private static Pattern except = Pattern.compile("(^| )except .*$");

  public static String searchForOrderBy(String str) {
    Matcher matcher = order.matcher(str);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }

  public static String searchForWhere(String str) {
    Matcher matcher = where.matcher(str);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }

  public static String searchForExcept(String str) {
    Matcher matcher = except.matcher(str);
    if (matcher.find()) {
      return matcher.group();
    }
    return null;
  }

  public static Clause parse(String script) {
    Clause clause = new Clause();
    script = script.replaceAll("^[a-zA-Z]+\\(\\)", "").trim();
    String orderBy = searchForOrderBy(script);
    if (orderBy != null) {
      script = script.replace(orderBy, "").trim();
    }
    String where = searchForWhere(script);
    if (where != null) {
      script = script.replace(where, "").trim();
    }
    String except = searchForExcept(script);
    clause.where(where).orderBy(orderBy);
    if (except != null) {
      except = except.replace("except", "").trim();
      String[] split = except.split(",");
      for (String s : split) {
        clause.except(s);
      }
    }
    return clause;
  }
}
